import { isNull, isUndefined } from "mmb";
import {
  getBgsThirdpartyOpSafely,
  getMetadata,
  getOptionsOfLight,
  wrapperGrpcError,
} from "../grpc-client/grpcAdapter";
import * as thirdpartypb from "../grpc-client/others/thirdparty_pb";

export interface GetUploadTokenParams {
  bucket: string
  expires?: number,
}


export const getUploadToken = async ({bucket, expires}: GetUploadTokenParams): Promise<string>  => {
  const cl = getBgsThirdpartyOpSafely();
  const req = new thirdpartypb.QiniuGetUploadTokenReq();

  req.setBucket(bucket);
  if (!isUndefined(expires)) {
    req.setExpires(expires)
  }
  
  return new Promise((resolve, reject) => {
    cl.qiniuGetUploadToken(req, getMetadata(), getOptionsOfLight(), (err, res) => {
      if (!isNull(err)) {
        reject(wrapperGrpcError(err.details));
        return;
      }
      resolve(res.getUtoken());
    });
  });
}